from django.shortcuts import render
from django.contrib.auth.decorators import login_required
from django.contrib.auth.models import User
from django.http import JsonResponse
from .models import UserProfile

# Create your views here.

@login_required
def user_list(request):
    """获取当前用户可见的用户列表"""
    # 超级管理员可以看到所有用户
    if request.user.is_superuser:
        users = User.objects.all()
    elif hasattr(request.user, 'profile'):
        # 获取自己和所有下级
        subordinate_users = request.user.profile.get_all_subordinates()
        subordinate_ids = [u.id for u in subordinate_users]
        subordinate_ids.append(request.user.id)
        users = User.objects.filter(id__in=subordinate_ids)
    else:
        # 只能看到自己
        users = User.objects.filter(id=request.user.id)
    
    # 构建用户数据
    user_data = []
    for user in users:
        profile = getattr(user, 'profile', None)
        user_data.append({
            'id': user.id,
            'username': user.username,
            'email': user.email,
            'first_name': user.first_name,
            'last_name': user.last_name,
            'department': profile.department if profile else '',
            'position': profile.position if profile else '',
            'phone': profile.phone if profile else '',
            'employee_id': profile.employee_id if profile else '',
            'supervisor': profile.supervisor.username if profile and profile.supervisor else '',
            'is_active': user.is_active,
        })
    
    return render(request, 'users/user_list.html', {'users': user_data})

@login_required
def user_detail(request, user_id):
    """获取用户详情"""
    try:
        user = User.objects.get(id=user_id)
        
        # 检查权限
        if not request.user.is_superuser:
            if hasattr(request.user, 'profile'):
                subordinate_users = request.user.profile.get_all_subordinates()
                subordinate_ids = [u.id for u in subordinate_users]
                subordinate_ids.append(request.user.id)
                if user_id not in subordinate_ids:
                    return JsonResponse({'error': '无权查看该用户'}, status=403)
            elif user_id != request.user.id:
                return JsonResponse({'error': '无权查看该用户'}, status=403)
        
        profile = getattr(user, 'profile', None)
        data = {
            'id': user.id,
            'username': user.username,
            'email': user.email,
            'first_name': user.first_name,
            'last_name': user.last_name,
            'department': profile.department if profile else '',
            'position': profile.position if profile else '',
            'phone': profile.phone if profile else '',
            'employee_id': profile.employee_id if profile else '',
            'supervisor': profile.supervisor.username if profile and profile.supervisor else '',
            'hire_date': str(profile.hire_date) if profile and profile.hire_date else '',
            'remarks': profile.remarks if profile else '',
            'groups': [g.name for g in user.groups.all()],
            'is_active': user.is_active,
            'is_staff': user.is_staff,
        }
        return JsonResponse(data)
    except User.DoesNotExist:
        return JsonResponse({'error': '用户不存在'}, status=404)

